﻿using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WallpaperForm.Entities;
using Yitter.IdGenerator;

namespace WallpaperForm
{
    public partial class ReNameForm : Form
    {
        private ZyWallpaperContext _dbContext;
        public ReNameForm()
        {
            InitializeComponent();
            _dbContext = new ZyWallpaperContext();
        }
        private void ReNameForm_Load(object sender, EventArgs e)
        {
            lv_log.View = View.Details;
            lv_log.Columns.Add("信息", 600);
            showLog("初始化程序！");
        }


        delegate bool ShowLogDelegate(string logStr);
        /// <summary>
        /// 显示日志
        /// </summary>
        /// <param name="log_str"></param>
        /// <returns></returns>
        bool showLog(string log_str)
        {
            Func<string, bool> log = str1 =>
            {
                lv_log.Items.Add(new ListViewItem(str1));
                lv_log.EnsureVisible(lv_log.Items.Count - 1);
                return true;
            };
            // 要调用的方法的委托
            ShowLogDelegate funDelegate = new ShowLogDelegate(log);

            /*========================================================
             * 使用this.BeginInvoke方法
             * （也可以使用this.Invoke()方法）
            ========================================================*/

            // this.BeginInvoke(被调用的方法的委托，要传递的参数[Object数组])
            IAsyncResult aResult = this.BeginInvoke(funDelegate, log_str);

            // 用于等待异步操作完成(-1表示无限期等待)
            aResult.AsyncWaitHandle.WaitOne(1);

            // 使用this.EndInvoke方法获得返回值
            bool ret = (bool)this.EndInvoke(aResult);
            return ret;
        }


        private void btn_select_dir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择wallpaper视频所在文件夹";
            dialog.SelectedPath = tb_dir.Text;
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    MessageBox.Show(this, "文件夹路径不能为空", "提示");
                    return;
                }
                tb_dir.Text = dialog.SelectedPath;
            }
        }

        /// <summary>
        /// 初始化至数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void initBtn_Click(object sender, EventArgs e)
        {
            string path = tb_dir.Text;
            if ((!string.IsNullOrWhiteSpace(path)) && Directory.Exists(path))
            {
                var res = getFileList(path);
                if (res.dirNames.Count > 0)
                {
                    var dbDirs = await _dbContext.WallpaperGroups.ToListAsync();
                    var insert = res.dirNames.Except(dbDirs.Select(x => x.GroupName)).ToList();
                    var groupInsert = insert.Select(x => new WallpaperGroup
                    {
                        Description = null,
                        GroupName = x,
                        Id = YitIdHelper.NextId(),

                    });
                    await _dbContext.AddRangeAsync(groupInsert);
                }
                if (res.objs.Count > 0)
                {
                    var objs = res.objs.Select(x => new WallpaperItem
                    {
                        Description = x.description,
                        DirPath = x.dirPath,
                        FileName = x.file,
                        FileSizeMB = x.fileSizeMB,
                        Id = YitIdHelper.NextId(),
                        Preview = x.preview,
                        Tags = string.Join(',', x.tags.ToArray()),
                        Title = x.title,
                        Type = x.type,
                        GroupName = x.groupName,
                        FullPath = Path.Combine(x.dirPath, x.file)
                    }).ToList();
                    await _dbContext.WallpaperItems.AddRangeAsync(objs);
                    showLog($"文件夹初始化成功，文件个数：{res.objs.Count}");
                }

                await _dbContext.SaveChangesAsync();
            }
        }
        /// <summary>
        /// 读取文件对象
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private ObjectFile getFileObj(string path)
        {
            var fileStream = new FileStream(path + "\\project.json", FileMode.Open);
            var bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, bytes.Length);
            var obj = JsonConvert.DeserializeObject<ObjectFile>(Encoding.UTF8.GetString(bytes));
            obj.dirPath = path;
            obj.objKey = Guid.NewGuid().ToString("N");
            if (File.Exists(Path.Combine(obj.dirPath, obj.file)))
            {
                var fileSizeBytes = new FileInfo(Path.Combine(obj.dirPath, obj.file)).Length;
                obj.fileSizeMB = (double)fileSizeBytes / 1024 / 1024;
            }
            fileStream.Close();
            fileStream.Dispose();
            return obj;
        }
        /// <summary>
        /// 获得文件对象列表
        /// </summary>
        /// <param name="path"></param>
        /// <param name="types"></param>
        private (List<ObjectFile> objs, List<string> dirNames) getFileList(string path)
        {
            if ((!string.IsNullOrWhiteSpace(path)) && Directory.Exists(path))
            {
                var dirsName = new List<string>();
                string[] files = Directory.GetFiles(path);
                var fileList = new List<ObjectFile>();
                if (files.Contains(path + "\\project.json"))
                {
                    var dirFullName = Path.GetDirectoryName(path);
                    var dir = Path.GetFileName(dirFullName);
                    var obj = getFileObj(path);
                    if (dir != null)
                    {
                        obj.groupName = dir;
                        dirsName.Add(dir);
                    }
                    fileList.Add(obj);
                }
                else if (Directory.GetDirectories(path).Length > 0)
                {
                    string[] dirs = Directory.GetDirectories(path);
                    foreach (string d in dirs)
                    {
                        try
                        {
                            var res = getFileList(d);
                            fileList.AddRange(res.objs);
                            dirsName.AddRange(res.dirNames);
                        }
                        catch { }
                    }
                }
                return (fileList, dirsName);
            }
            return (new List<ObjectFile>(), new List<string>());
        }
        /// <summary>
        /// 视频筛选按钮点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void videoFilterBtn_Click(object sender, EventArgs e)
        {
            showLog($"筛选视频，目标文件地址：{tbDestPath.Text}");
            var videosForm = new Videos(tbDestPath.Text, new Unit.ShowLogDelegate(showLog));
            videosForm.Show();
        }

        private void videoGroupBtn_Click(object sender, EventArgs e)
        {
            showLog($"筛选视频，目标文件地址：{tbDestPath.Text}");
            var groupForm = new Group(tbDestPath.Text, new Unit.ShowLogDelegate(showLog));
            groupForm.Show();
        }
    }
}